package network;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 自定义Gson转换工厂
 * 由于后台data接口返回正常和异常的data数据格式不一样,采泛型T传入时,会引起Gson解析出错
 * 所以先通过GsonResponseBodyConverter对ret和info对行预解析
 *
 * @author: xiaoluo
 * @date: 2017-03-02 16:32
 */
public class GsonResponseFactory extends Converter.Factory {
    public static GsonResponseFactory create() {
        return create(new Gson());
    }

    public static GsonResponseFactory create(Gson gson) {
        return new GsonResponseFactory(gson);
    }

    private final Gson gson;

    private GsonResponseFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new TupaiResponseConverter<>(gson, type);
    }

    @Override
    public Converter<?,
            RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new GsonRequestBodyConverter<>(gson, adapter);
    }
}